<template>
  <div class="pub-item">
    <div class="user-box" v-if="user.id">
      <el-avatar size="small" :src="user.avatar" />
    </div>
    <div class="user-box" v-else @click="sa.goLogin()">
      <svg-icon icon-class="user"></svg-icon>
    </div>
    <div class="pub-item__operations">
      <el-input v-model.trim="pubContent" type="textarea" rows="2" :placeholder="placeholderText" maxlength="500"
        show-word-limit :disabled="!user.id" @input="debounceInput" />
      <el-button class="pub-item__button" :class="{ show: pubContent }" @click="handleSubmit">
        评论
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'PubItem',
  props: {
    user: {
      type: Object,
      required: true
    },
    note: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      pubContent: this.note
    }
  },
  computed: {
    placeholderText() {
      return this.user.id ? '请友善评论' : '请登录，后评论'
    }
  },
  watch: {
    note(newVal) {
      this.pubContent = newVal
    }
  },
  methods: {
    /**
     * 防抖处理输入事件
     * @param {string} value - 输入框内容
     */
    debounceInput: _.debounce(function (value) {
      this.$emit('update:note', value)
    }, 300),

    /**
     * 处理提交事件
     * 触发父组件的submit事件
     */
    handleSubmit() {
      this.$emit('submit')
    }
  },

  /**
   * 组件创建时检查lodash依赖
   */
  created() {
    // 确保lodash已加载
    if (!window._) {
      console.error('Lodash is required for debounce functionality')
    }
  }
}
</script>

<style lang="scss" scoped>
.pub-item {
  display: flex;
  width: 100%;
  padding: 10px 5px;
}

.user-box {
  margin: 5px;
  width: 50px;
  cursor: pointer;

  img {
    height: 20px;
    width: 20px;
    border-radius: 50px;
  }
}

.pub-item__operations {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;

  ::v-deep .el-textarea__inner {
    border-radius: 6px;
    border-color: #dcdfe6;
    transition: all 0.3s ease;

    &:focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }

    &::placeholder {
      color: #909399;
      font-size: 14px;
    }
  }
}

.pub-item__button {
  width: 80px;
  height: 32px;
  border-radius: 6px;
  cursor: pointer;
  align-self: flex-end;
  margin-top: 8px;
  background-color: #409eff;
  color: #fff;
  border: none;
  transition: all 0.3s ease;
  opacity: 0;
  transform: translateY(10px);
  visibility: hidden;

  &.show {
    opacity: 1;
    transform: translateY(0);
    visibility: visible;
  }

  &:hover {
    background-color: #66b1ff;
  }

  &:active {
    background-color: #3a8ee6;
  }
}

@media (max-width: 768px) {
  .pub-item__operations {
    gap: 6px;

    ::v-deep .el-textarea__inner {
      font-size: 14px;
    }
  }

  .pub-item__button {
    width: 100%;
    margin-top: 6px;
    font-size: 14px;
  }
}
</style>
